import axios, { AxiosInstance } from "axios";
import { ElMessage } from "element-plus";
import router from "@/router";

export const baseURL: string = "https://yxxf.guojutech.net/api/";
// export const baseURL: string = "http://172.18.10.13:15050/";
const baseUploadUrl = `${baseURL}/manage/v1/storage/upload?dir=`;

//上传图片
export const uploadUrl = (fileId: string): string =>
  `${baseUploadUrl}${fileId}`;

export interface ApiResult<T> {
  success: boolean;
  code: number;
  msg: string;
  data: T;
}

const request: AxiosInstance = axios.create({
  baseURL,
  timeout: 200000,
});

// 添加请求拦截器
request.interceptors.request.use(
  (config) => {
    // 在发送请求之前做些什么
    const xAuthToken: string | null = localStorage.getItem("x-auth-token");
    if (xAuthToken != null) {
      config.headers["x-auth-token"] = xAuthToken;
    }
    return config;
  },
  (error: any) => {
    // 处理请求错误
    return Promise.reject(error);
  },
);

// 添加响应拦截器
request.interceptors.response.use(
  (response) => {
    // 对响应数据做点什么
    if (response.headers["x-auth-token"]) {
      localStorage.setItem("x-auth-token", response.headers["x-auth-token"]);
    }

    if (response?.data?.code === 401) {
      sessionStorage.removeItem("userStore");
      router.replace({ path: "/login", replace: true }).then();
    }
    return response;
  },
  (error: any) => {
    ElMessage.error(error.message);
    return Promise.reject(error);
  },
);

export async function get<T>(
  url: string,
  params?: any,
  config?: any,
): Promise<ApiResult<T>> {
  const response = await request.get<ApiResult<T>>(url, { params, ...config });
  return response.data;
}

export async function post<T>(
  url: string,
  data?: any,
  config?: any,
): Promise<ApiResult<T>> {
  const response = await request.post<ApiResult<T>>(url, data, config);
  return response.data;
}
export async function fetchDelete<T>(
  url: string,
  params?: any,
  config?: any,
): Promise<ApiResult<T>> {
  const response = await request.delete<ApiResult<T>>(url, {
    params,
    ...config,
  });
  return response.data;
}
export async function fetchPut<T>(
  url: string,
  data?: any,
  config?: any,
): Promise<ApiResult<T>> {
  const response = await request.put<ApiResult<T>>(url, data, config);
  return response.data;
}
